<template>
    <div class="box loginBox">
      <van-nav-bar
        title="登录"
        right-text="注册"
          left-arrow
          @click-left="onClickLeft"
          @click-right="onClickRight"
      />
      <div class="header">
        <div class="title">
          <van-icon name="smile-o" />
          <span>甄优选</span>
        </div>
      </div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="tel"
          name="tel"
          placeholder="请输入手机号"
          :rules="[{ required: true, message: '手机号有误', validator: telTest }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '密码有误', validator: pw2Test }]"
        />
        <div style="margin: 16px;">
          <van-button round block type="danger" native-type="submit">登录</van-button>
        </div>
      </van-form>
    </div>
</template>
<script>
import Vue from 'vue'
import { login } from '@/api/request.js'
import { NavBar, Form, Field, Toast, Button, Icon } from 'vant'

Vue.use(NavBar)
Vue.use(Form)
Vue.use(Field)
Vue.use(Toast)
Vue.use(Button)
Vue.use(Icon)

export default {
  data () {
    return {
      username: '',
      password: '',
      tel: ''
    }
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    onClickRight () {
      this.$router.push('/register')
    },
    onSubmit (v) {
      const that = this
      login(v).then(data => {
        switch (data.data.code) {
          case 200:
            sessionStorage.setItem('token', data.data.token)
            sessionStorage.setItem('userId', data.data.msg)
            sessionStorage.setItem('isLogin', 'ok')
            Toast({
              message: '登录成功',
              icon: 'like-o',
              onClose () {
                that.$router.push('/home')
              }
            })
            break
          case 201:
            Toast.fail('用户名不存在')
            break
          case 202:
            Toast.fail('密码错误')
            break
        }
      })
    },
    telTest () {
      return /^1[3-9]\d{9}$/.test(this.tel)
    },
    pw2Test () {
      return /^.{1,10}$/.test(this.password2)
    }
  }
}
</script>
<style lang="scss">
.loginBox{
  .van-nav-bar__left{
    i{
      color: #000;
    }
  }
  .van-nav-bar__title{
    font-family: KaiTi;
    font-size: 24px;
    font-weight: bolder;
  }
  .van-nav-bar__text{
    color: #ee0a24;
  }
  .header{
    padding: 0.6rem 0;
    .title{
      text-align: center;
      i{
        font-size: 30px;
        margin-right: 0.06rem;
      }
      span{
        font-size: 40px;
        font-family: KaiTi;
      }
    }
  }
}
</style>
